package cc.messcat.web.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.constant.CommonRedisConstant;
import cc.messcat.common.model.Pager;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.entity.area.Area;
import cc.messcat.entity.fupin.PoorFamily;
import cc.messcat.entity.level.UserLevel;
import cc.messcat.entity.system.McUser;
import cc.messcat.log.OperationLog;
import cc.messcat.service.area.AreaService;
import cc.messcat.service.fupin.FamilyService;
import cc.messcat.service.fupin.PoorFamilyService;
import cc.messcat.service.fupin.PoorVillageService;
import cc.messcat.service.system.UserService;
import cc.messcat.util.Collections;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * 地区功能模块
 *
 * @author John
 */
@Controller
@RequestMapping("/area")
public class AreaController {

	@Autowired
	private AreaService areaService;

	@Autowired
	private PoorFamilyService poorFamilyService;

	@Autowired
	private PoorVillageService poorVillageService;

	@Autowired
	private FamilyService familyService;

	@Autowired
	private UserService userService;
	
    @Autowired
    private CacheManager manager;

	@RequestMapping(value = "/getAllAreas", method = RequestMethod.POST)
	@ResponseBody
	public Object getAllAreas(HttpSession session, Integer level, @RequestParam(name = "keyword", required = false) String keyword)
		throws Exception {
		McUser user = (McUser) session.getAttribute("user");
		Long areaId = user.getAreaId();
		UserLevel userLevel = user.getUserLevel();
		if (level == userLevel.getLevel()) {
			Area area0 = null;
			List list = null;
			Object o = session.getAttribute("area" + userLevel.getLevel());
			if (o instanceof java.util.ArrayList) {
				list = (List) o;
				area0 = (Area) list.get(0);
			} else {
				area0 = (Area) o;
			}
			List<Area> areas3 = new ArrayList<>();
			areas3.add(area0);
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, areas3);
		}
		List<Area> areas3 = (List<Area>) session.getAttribute("area" + level);
		// 模糊查詢
		if (StringUtils.isNotBlank(keyword)) {
			List<Area> result = new ArrayList<>();
			for (Area e : areas3) {
				// 如果包含
				if (StringUtils.isNotBlank(e.getArea()) ? e.getArea().contains(keyword) : false) {
					result.add(e);
				}
			}
			areas3 = result;
		}
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, areas3);
	}

	// 查询
	/*
	 * @RequestMapping(value = "/findAllarea" , method = RequestMethod.POST)
	 * 
	 * @ResponseBody public Object findAllarea(HttpServletResponse
	 * response,Model model) throws Exception { areaService.retrieveAllarea();
	 * //List<Area> areas3 = (List<Area>) session.getAttribute("area" + level);
	 * //System.out.println(areaService.retrieveAllarea().get(0).getArea()); //
	 * System.out.println(areaService.retrieveAllarea().get(0).getArea());
	 * response.setHeader("Content-type", "text/html;charset=UTF-8");
	 * //response.setCharacterEncoding("UTF-8"); Map map=new HashMap();
	 * map.put("area", areaService.retrieveAllarea());
	 * model.addAttribute("area", areaService.retrieveAllarea()); //
	 * response.getWriter().print(JSONObject.fromObject(map).toString());
	 * List<Area> resultList = areaService.retrieveAllarea(); return null; }
	 */

	// 模糊县区、行政代码查询
//	@OperationLog(desc = "模糊县区、行政代码查询", module = "区域获取")
	@RequestMapping(value = "/findvaguearea", method = RequestMethod.POST)
	@ResponseBody
	@SuppressWarnings("all")
	public Object findvaguearea(Integer pageNo, Integer pageSize, Long fatherId, String area, String areaCode)
			throws Exception {
		if (pageNo == null || pageNo < 1) {
			pageNo = 1;
		}
		if (pageSize == null || pageSize < 1) {
			pageSize = 10;
		}
		Pager<Area> areas = areaService.retrieveAllvaguearea(pageNo, pageSize, fatherId, area, areaCode);

		if (fatherId == null && !"".equals(fatherId)) {
			List<Map> result = new ArrayList<>();
			List<Area> country = areaService.retrieveAllvaguearea(1, 5000, 3L, null, null).getResultList();
			Map<Long, String> temp = new HashMap<>();
			for (Area e : country) {
				temp.put(e.getId(), e.getArea());
			}
			for (Area e : areas.getResultList()) {
				result.add(Collections.generateHashMap(
						"id",e.getId(),
						"area",temp.get(e.getFatherId()) + " " + e.getArea(),
						"areaCode",e.getAreaCode(),
						"fatherId",e.getFatherId()));
			}
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, 
					new Pager(pageSize,pageNo,areas.getRowCount(),result));
		}
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, areas);
	}

	// 查询
	@RequestMapping(value = "/findarea", method = RequestMethod.POST)
	@ResponseBody
	public Object findarea(HttpServletResponse response, Model model, Long fatherId) throws Exception {
		List<Area> areas = areaService.retrieveAllarea(fatherId);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, areas);
	}

	/**
	 * 根据登录权限查询区域
	 * 
	 * @throws Exception
	 */
//	@OperationLog(desc = "根据登录权限查询区域", module = "区域获取")
	@RequestMapping(value = "/areaAuthorization")
	@ResponseBody
	public Object areaAuthorization(HttpServletResponse response, HttpSession session, Model model, Long fatherId)
		throws Exception {
		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		if (fatherId == null) {
			fatherId = 0L;
		}
		List<Area> areas = areaService.areaAuthorization(user, fatherId);

		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, areas);
	}

	// 翻页查询
	@RequestMapping(value = "/findareapager", method = RequestMethod.POST)
	@ResponseBody
	public Object findareapager(Long fatherId, Integer pageNo, Integer pageSize) throws Exception {
		Pager pager = areaService.getPage(fatherId, pageNo, pageSize);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
	}

	// 根据Id查询
//	@OperationLog(desc = "根据id县、乡、村查询", module = "区域获取")
	@RequestMapping(value = "/findareaById", method = RequestMethod.POST)
	@ResponseBody
	public Object findareaById(Long id) throws Exception {
		List<Area> areas = areaService.retrieveAreaById(id);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, areas);
	}

	// 根据id和fatherId查询
	@RequestMapping(value = "/findareaByIdfathid", method = RequestMethod.POST)
	@ResponseBody
	public Object findareaByIdfathid(Long id, Long fatherId) throws Exception {
		List<Area> areas = areaService.retrieveAreaByIdfathid(id, fatherId);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, areas);
	}

	// 根据条件查询查询
	@RequestMapping(value = "/findareaByCondition", method = RequestMethod.POST)
	@ResponseBody
	public Object findareaBy(HttpServletResponse response, Model model, Long fatherId, String condition) throws Exception {
		List<Area> areas = areaService.retrieveAllarea(fatherId);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, areas);
	}

	// 删除
	@OperationLog(desc = "删除县、乡、村", module = "系统配置")
	@RequestMapping(value = "/delectarea", method = RequestMethod.POST)
	@ResponseBody
	public Object delectarea(Long id, HttpSession session) throws Exception {
		Area area = areaService.getByAreaID(id);

		if (area != null && area.getFatherId() <= 3) {
			List<Area> areaList = areaService.findAreasByParentId(id);
			if (areaList != null && !areaList.isEmpty()) {
				return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "该行政区域已经绑定下辖区域，无法删除", "failure");
			}
		}

		if (area != null && area.getFatherId() > 3) {
			if (poorVillageService.getVillageByAreaId(id) != null) {
				return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "该行政村已经绑定贫困村，无法删除", "failure");
			}
		}
		if(id != null) {
			List<PoorFamily> list = poorFamilyService.getPoorFamilyByAreaID(id);
			if(!Collections.isEmpty(list)) return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "该行政区域已经绑定贫困户，无法删除", "failure"); 
		}
		areaService.removearea(id);

		// session数据覆盖
		updateSession(session);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_DELETE_SUCCESS, id);
	}

	// 添加
	@OperationLog(desc = "添加县、乡、村", module = "系统配置")
	@RequestMapping(value = "/addarea", method = RequestMethod.POST)
	@ResponseBody
	public Object addarea(Area area, HttpSession session) throws Exception {
		/*
		 * area.setArea("广州2"); area.setAreaCode("130434213229");
		 * area.setFatherId(25L); area.setType("777");
		 */
		areaService.addArea(area);
		// session数据覆盖
		updateSession(session);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS, area);
	}

	// 修改
	@OperationLog(desc = "修改县、乡、村", module = "系统配置")
	@RequestMapping(value = "/updatearea", method = RequestMethod.POST)
	@ResponseBody
	public Object updatearea(Long id, String area, String areaCode, Long fatherId, HttpSession session) throws Exception {
		Area tempArea = areaService.retrieveObject(id);
		tempArea.setArea(area);
		tempArea.setAreaCode(areaCode);
		tempArea.setFatherId(fatherId);
		areaService.modifyArea(tempArea);

		// session数据覆盖
		updateSession(session);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS);
	}

	// url:area/getAreaHasVillageInfo

	/**
	 * 通过 fatherID 查询已经关联了村子的地区
	 * 
	 * @param fatherId
	 * @return
	 */
	@RequestMapping(value = "/getAreaHasVillageInfo")
	@ResponseBody
	public Object getAreaHasVillageInfo(Long fatherId) {
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS,
			areaService.getAreaHasVillageInfo(fatherId));
	}

	/**
	 * 首页 收入信息(魏县下每个乡镇的人均存收入)
	 */
	@ResponseBody
	@SuppressWarnings("all")
	@RequestMapping(value = "income", method = { RequestMethod.GET })
	public Object income(HttpSession session) {
		List result= new ArrayList<>(0);
		Element element = manager.getCache("indexStatistics").get("income");
		if(element != null) {
			result = (List) element.getObjectValue();
		} else {
			result = poorFamilyService.complexQueryIncomeInfo();
		}
		 return new ResponseBean(CommonConstant.SUCCESS_CODE_200,
		 CommonConstant.MSG_FIND_SUCCESS, result);
//		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, new ArrayList<>());
	}

	// 校验AreaCode
	@RequestMapping(value = "/verificAreaCode", method = RequestMethod.POST)
	@ResponseBody
	public Object verificAreaCode(String areaCode) throws Exception {

		Area area = areaService.getAreaByCode(areaCode);
		return area == null ? new ResponseBean(CommonConstant.SUCCESS_CODE_200, "没有重复数据")
			: new ResponseBean(CommonConstant.FAIL_CODE_400, "有重复数据");

	}

	/**
	 * 根据原设计更新session属性
	 * @param session
	 */
	private void updateSession(HttpSession session) {
		// 根据原设计更新session属性
		McUser user = (McUser) session.getAttribute("user");
		Long areaId = user.getAreaId();
		UserLevel userLevel = user.getUserLevel();
		int level = userLevel.getLevel();
		if (0 == userLevel.getLevel()) {
			level++;
		}
		// session数据覆盖
		Area area0;
		if (0L == areaId) {
			area0 = areaService.findAreasByParentId(areaId).get(0);
		} else {
			area0 = areaService.getByAreaID(areaId);
		}

		List<Area> areas = new ArrayList<>();
		areas.add(area0);
		List<Area> areas1 = new ArrayList<>();
		areas1.add(area0);
		session.setAttribute("area" + level, areas);
		System.out.println("***************area" + level + ":" + areas1.size());
		while (level < 5) {
			List<Area> areas3 = new ArrayList<>();
			for (Area a : areas1) {
				List<Area> areas2 = areaService.findAreasByParentId(a.getId());
				areas3.addAll(areas2);
			}
			session.setAttribute("area" + (level + 1), areas3);
			areas1.clear();
			areas1.addAll(areas3);
			level++;
			System.out.println("***************area" + level + ":" + areas3.size());
		}
		areas1.clear();
		// end
	}

	/**
	 * 区域全表数据获取
	 */
	public void getAllArea() {
		List<Area> allArea = areaService.getAllArea();
	}
}
